<!DOCTYPE html>
<html lang="en">
<head><!-- hexo injector head_begin start -->
        <link rel="preconnect" href="https://blog.fantasyke.cn/picx-images-hosting" crossorigin=""><!-- hexo injector head_begin end -->
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/uploads/avatar.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/uploads/avatar.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="0qBBGdG7vYORyT5XLZRUqQZ_y5kKYhgyUwNqjSIImg0">
  <meta name="msvalidate.01" content="63C90D0EC3DA6C31FD109132B7BEF502">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Zen+Maru+Gothic:300,300italic,400,400italic,700,700italic%7CZCOOL+XiaoWei:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha256-5eIC48iZUHmSlSUz9XtjRyK2mzQkHScZY1WdMaoz74E=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.31/fancybox/fancybox.css" integrity="sha256-gkQVf8UKZgQ0HyuxL/VnacadJ+D2Kox2TCEBuNQg5+w=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.fantasyke.cn","root":"/","images":"/images","scheme":"Mist","darkmode":false,"version":"8.21.1","exturl":true,"sidebar":{"position":"right","width_expanded":350,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":null},"fold":{"enable":true,"height":500},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":true,"nav":{"gitalk":{"text":"gitalk","order":-1}},"activeClass":"gitalk"},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="消息类型的演进 在.NET Core中使用gRPC 多项目之间共享&#96;proto&#96;文件">
<meta property="og:type" content="article">
<meta property="og:title" content="gRPC in ASP.NET Core">
<meta property="og:url" content="https://blog.fantasyke.cn/posts/34332/index.html">
<meta property="og:site_name" content="Fantasy&#39;Ke Blog">
<meta property="og:description" content="消息类型的演进 在.NET Core中使用gRPC 多项目之间共享&#96;proto&#96;文件">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2023-06-28T13:36:00.000Z">
<meta property="article:modified_time" content="2024-12-17T06:36:35.365Z">
<meta property="article:author" content="Fantasy-ke">
<meta property="article:tag" content="ASP.NET Core">
<meta property="article:tag" content="gRPC">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://blog.fantasyke.cn/posts/34332/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"en","comments":true,"permalink":"https://blog.fantasyke.cn/posts/34332/","path":"posts/34332/","title":"gRPC in ASP.NET Core"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>gRPC in ASP.NET Core | Fantasy'Ke Blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="Fantasy'Ke Blog" type="application/atom+xml">
<style>.darkmode--activated{--body-bg-color:#282828;--content-bg-color:#333;--card-bg-color:#555;--text-color:#ccc;--blockquote-color:#bbb;--link-color:#ccc;--link-hover-color:#eee;--brand-color:#ddd;--brand-hover-color:#ddd;--table-row-odd-bg-color:#282828;--table-row-hover-bg-color:#363636;--menu-item-bg-color:#555;--btn-default-bg:#222;--btn-default-color:#ccc;--btn-default-border-color:#555;--btn-default-hover-bg:#666;--btn-default-hover-color:#ccc;--btn-default-hover-border-color:#666;--highlight-background:#282b2e;--highlight-foreground:#a9b7c6;--highlight-gutter-background:#34393d;--highlight-gutter-foreground:#9ca9b6}.darkmode--activated img{opacity:.75}.darkmode--activated img:hover{opacity:.9}.darkmode--activated code{color:#69dbdc;background:0 0}button.darkmode-toggle{z-index:9999}.darkmode-ignore,img{display:flex!important}.beian img{display:inline-block!important}</style></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Fantasy'Ke Blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="Search" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a></li><li class="menu-item menu-item-photos"><a href="/photos/" rel="section"><i class="fas fa-camera-retro fa-fw"></i>photos</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="Searching..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">1.</span> <span class="nav-text"> 开发环境</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-2"><span class="nav-number">1.1.</span> <span class="nav-text"> VSCode</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-3"><span class="nav-number">2.</span> <span class="nav-text"> 消息类型的演进</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-4"><span class="nav-number">2.1.</span> <span class="nav-text"> 更新消息类型的规则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-5"><span class="nav-number">2.2.</span> <span class="nav-text"> 默认值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-6"><span class="nav-number">2.3.</span> <span class="nav-text"> 枚举</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-7"><span class="nav-number">3.</span> <span class="nav-text"> 在.NET Core中使用gRPC</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-8"><span class="nav-number">3.1.</span> <span class="nav-text"> ASP.NET Core</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-9"><span class="nav-number">3.2.</span> <span class="nav-text"> .NET Core</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-10"><span class="nav-number">3.3.</span> <span class="nav-text"> 引包之后的操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-11"><span class="nav-number">3.4.</span> <span class="nav-text"> 作为服务端</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-12"><span class="nav-number">3.5.</span> <span class="nav-text"> 作为客户端</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-13"><span class="nav-number">4.</span> <span class="nav-text"> 上代码</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-14"><span class="nav-number">4.1.</span> <span class="nav-text"> 服务端</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-15"><span class="nav-number">4.1.1.</span> <span class="nav-text"> 创建目录</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-16"><span class="nav-number">4.1.2.</span> <span class="nav-text"> 编写proto</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-17"><span class="nav-number">4.1.3.</span> <span class="nav-text"> 编写测试数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-18"><span class="nav-number">4.1.4.</span> <span class="nav-text"> 编写Service</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-19"><span class="nav-number">4.1.5.</span> <span class="nav-text"> 修改Startup</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-20"><span class="nav-number">4.1.6.</span> <span class="nav-text"> 运行项目</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-21"><span class="nav-number">4.2.</span> <span class="nav-text"> 客户端</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-22"><span class="nav-number">4.2.1.</span> <span class="nav-text"> 创建项目</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-23"><span class="nav-number">4.2.2.</span> <span class="nav-text"> 复制proto文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-24"><span class="nav-number">4.2.3.</span> <span class="nav-text"> 修改Program.cs</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-25"><span class="nav-number">4.2.4.</span> <span class="nav-text"> 运行项目</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-26"><span class="nav-number">5.</span> <span class="nav-text"> 日志和异常</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-27"><span class="nav-number">5.1.</span> <span class="nav-text"> 日志</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-28"><span class="nav-number">5.1.1.</span> <span class="nav-text"> ASP.NET Core</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-29"><span class="nav-number">5.1.2.</span> <span class="nav-text"> .NET Core控制台</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-30"><span class="nav-number">5.2.</span> <span class="nav-text"> 异常</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-31"><span class="nav-number">6.</span> <span class="nav-text"> 关于JWT授权</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-32"><span class="nav-number">7.</span> <span class="nav-text"> 多项目之间共享proto文件</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Fantasy-ke"
      src="/uploads/avatar.png">
  <p class="site-author-name" itemprop="name">Fantasy-ke</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">36</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2ZhbnRhc3kta2U=" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;fantasy-ke"><i class="fab fa-github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly94LmNvbS9BX0RyZWFtZXJfSGFyZA==" title="Twitter → https:&#x2F;&#x2F;x.com&#x2F;A_Dreamer_Hard"><i class="fab fa-twitter fa-fw"></i>Twitter</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly93d3cueW91dHViZS5jb20vQCVFNSU5MSVBOCVFNiVBMiVBNi16OWk=" title="YouTube → https:&#x2F;&#x2F;www.youtube.com&#x2F;@%E5%91%A8%E6%A2%A6-z9i"><i class="fab fa-youtube fa-fw"></i>YouTube</span>
      </span>
  </div>
<div class="cc-license animated" itemprop="sponsor">
  <a href="https://www.netlify.com" class="cc-opacity" title="Deploy with Netlify → https://www.netlify.com" target="_blank"><img width="80" src="https://www.netlify.com/img/global/badges/netlify-dark.svg" alt="Netlify"></a>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css">
<div id="aplayer" style="position:relative;left;0;bottom:0;"></div>
<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/color-thief-don@2.0.2/src/color-thief.js"></script>
<script>
  const ap = new APlayer({
    container: document.getElementById('aplayer'),
    autoplay: false, //自动播放
    listFolded: true, //播放列表默认折叠
    listMaxHeight: 90, //播放列表最大高度
    order: 'list', //音频循环顺序, 可选值: 'list', 'random'
    loop: 'all', //音频循环播放, 可选值: 'all', 'one', 'none'
    theme: '#e9e9e9', //切换音频时的主题色，优先级低于audio.theme
    preload: 'none', //音频预加载，可选值: 'none', 'metadata', 'auto'
    mutex: true, //互斥，阻止多个播放器同时播放，当前播放器播放时暂停其他播放器
    lrcType: 3, //歌词格式，可选值：3（LRC文件歌词格式），1（JS字符串歌词格式）
    volume: 0.7, //默认音量，请注意播放器会记忆用户设置，用户手动设置音量后默认音量即失效
    fixed: false, //吸底模式（fixed:true），迷你模式（mini:true），普通模式（注释此行或者设置fixed:false）
    audio: [{
        name: '平凡之路',
        artist: '朴树',
        lrc: '/downloads/lrc/平凡之路-朴树.lrc',
        cover: 'http://p2.music.126.net/W_5XiCv3rGS1-J7EXpHSCQ==/18885211718782327.jpg?param=300x300',
        url: 'http://ws.stream.qqmusic.qq.com/C4000007nRJ74eQsF6.m4a?guid=942726817&vkey=64755357C5716983BEECE2981FEC3954F0DD03E7630EFF769D9C40C31F50D53E7D260CB63E22CE8F954B1144083716A1BABFC2093F8F1C14&uin=&fromtag=120032'
      },
      {
        name: '后会无期',
        artist: '徐良,汪苏泷',
        lrc: '/downloads/lrc/后会无期-G.E.M.邓紫棋.lrc',
        cover: 'http://p1.music.126.net/vpvPajo3kn88nHc7jUjeWQ==/5974746185758035.jpg?param=300x300',
        url: 'http://ws.stream.qqmusic.qq.com/C400004ECnYg0QNchK.m4a?guid=893251117&vkey=D9DCBB8C4A4CAF8550E97A2A574DE1231DFDD8BC0989CC724742C7B9831C4108E0A805A46E0F2B2A556228467C146B9C312E3E8B498614C7&uin=&fromtag=120032'
      }
    ]
  });

  // 实现切换音频时，根据音频的封面图片自适应主题色
  const colorThief = new ColorThief();
  const setTheme = (index) => {
    if (!ap.list.audios[index].theme) {
      colorThief.getColorAsync(ap.list.audios[index].cover, function(color) {
        ap.theme(`rgb(${color[0]}, ${color[1]}, ${color[2]})`, index);
      });
    }
  };
  setTheme(ap.list.index);
  ap.on('listswitch', (data) => {
    setTheme(data.index);
  });
</script>



        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          Links
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9mYW50YXN5LWtlLmdpdGh1Yi5pbw==" title="https:&#x2F;&#x2F;fantasy-ke.github.io">SunBlog</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9mYW50YXN5LWtlLmdpdGh1Yi5pbw==" title="https:&#x2F;&#x2F;fantasy-ke.github.io">做梦的努力者</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0ZhbnRhc3ktS2U=" title="https:&#x2F;&#x2F;github.com&#x2F;Fantasy-Ke">github</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9naXRlZS5jb20vZmFudGFzeV9rZQ==" title="https:&#x2F;&#x2F;gitee.com&#x2F;fantasy_ke">gitee</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly93d3cuY25ibG9ncy5jb20vZmFudGFzeS1rZQ==" title="https:&#x2F;&#x2F;www.cnblogs.com&#x2F;fantasy-ke">我的园子</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9hYnAuaW8v" title="https:&#x2F;&#x2F;abp.io&#x2F;">abp</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9hYnAuaW8vZG9jcy9sYXRlc3Qv" title="https:&#x2F;&#x2F;abp.io&#x2F;docs&#x2F;latest&#x2F;">abp doc</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9ibG9ncy5tYXNhc3RhY2suY29tLw==" title="https:&#x2F;&#x2F;blogs.masastack.com&#x2F;">masa blog</span>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    Related Posts
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/posts/59211/" rel="bookmark">
        <time class="popular-posts-time">2023-05-29</time>
        <br>
      RabbitMQ进阶
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="en">
    <link itemprop="mainEntityOfPage" href="https://blog.fantasyke.cn/posts/34332/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/avatar.png">
      <meta itemprop="name" content="Fantasy-ke">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Fantasy'Ke Blog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="gRPC in ASP.NET Core | Fantasy'Ke Blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          gRPC in ASP.NET Core
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2023-06-28 21:36:00" itemprop="dateCreated datePublished" datetime="2023-06-28T21:36:00+08:00">2023-06-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2024-12-17 14:36:35" itemprop="dateModified" datetime="2024-12-17T14:36:35+08:00">2024-12-17</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%9D%82%E4%B8%83%E6%9D%82%E5%85%AB%E7%9A%84%E7%A0%96/" itemprop="url" rel="index"><span itemprop="name">杂七杂八的砖</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="Views" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">Views: </span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="Word count in article">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">Word count in article: </span>
      <span>2.7k</span>
    </span>
    <span class="post-meta-item" title="Reading time">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">Reading time &asymp;</span>
      <span>10 mins.</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><!-- *   [开发环境](#%e5%bc%80%e5%8f%91%e7%8e%af%e5%a2%83)
    *   [VSCode](#vscode)
*   [消息类型的演进](#%e6%b6%88%e6%81%af%e7%b1%bb%e5%9e%8b%e7%9a%84%e6%bc%94%e8%bf%9b)
    *   [更新消息类型的规则](#%e6%9b%b4%e6%96%b0%e6%b6%88%e6%81%af%e7%b1%bb%e5%9e%8b%e7%9a%84%e8%a7%84%e5%88%99)
    *   [默认值](#%e9%bb%98%e8%ae%a4%e5%80%bc)
    *   [枚举](#%e6%9e%9a%e4%b8%be)
*   [在`.NET Core`中使用`gRPC`](#%e5%9c%a8net-core%e4%b8%ad%e4%bd%bf%e7%94%a8grpc)
    *   [`ASP.NET Core`](#aspnet-core)
    *   [`.NET Core`](#net-core)
    *   [引包之后的操作](#%e5%bc%95%e5%8c%85%e4%b9%8b%e5%90%8e%e7%9a%84%e6%93%8d%e4%bd%9c)
    *   [作为服务端](#%e4%bd%9c%e4%b8%ba%e6%9c%8d%e5%8a%a1%e7%ab%af)
    *   [作为客户端](#%e4%bd%9c%e4%b8%ba%e5%ae%a2%e6%88%b7%e7%ab%af)
*   [上代码](#%e4%b8%8a%e4%bb%a3%e7%a0%81)
    *   [服务端](#%e6%9c%8d%e5%8a%a1%e7%ab%af)
        *   [创建目录](#%e5%88%9b%e5%bb%ba%e7%9b%ae%e5%bd%95)
        *   [编写`proto`](#%e7%bc%96%e5%86%99proto)
        *   [编写测试数据](#%e7%bc%96%e5%86%99%e6%b5%8b%e8%af%95%e6%95%b0%e6%8d%ae)
        *   [编写`Service`](#%e7%bc%96%e5%86%99service)
        *   [修改`Startup`](#%e4%bf%ae%e6%94%b9startup)
        *   [运行项目](#%e8%bf%90%e8%a1%8c%e9%a1%b9%e7%9b%ae)
    *   [客户端](#%e5%ae%a2%e6%88%b7%e7%ab%af)
        *   [创建项目](#%e5%88%9b%e5%bb%ba%e9%a1%b9%e7%9b%ae)
        *   [复制`proto`文件](#%e5%a4%8d%e5%88%b6proto%e6%96%87%e4%bb%b6)
        *   [修改`Program.cs`](#%e4%bf%ae%e6%94%b9programcs)
        *   [运行项目](#%e8%bf%90%e8%a1%8c%e9%a1%b9%e7%9b%ae-1)
*   [日志和异常](#%e6%97%a5%e5%bf%97%e5%92%8c%e5%bc%82%e5%b8%b8)
    *   [日志](#%e6%97%a5%e5%bf%97)
        *   [ASP.NET Core](#aspnet-core-1)
        *   [.NET Core控制台](#net-core%e6%8e%a7%e5%88%b6%e5%8f%b0)
    *   [异常](#%e5%bc%82%e5%b8%b8)
*   [关于JWT授权](#%e5%85%b3%e4%ba%8ejwt%e6%8e%88%e6%9d%83)
*   [多项目之间共享`proto`文件](#%e5%a4%9a%e9%a1%b9%e7%9b%ae%e4%b9%8b%e9%97%b4%e5%85%b1%e4%ba%abproto%e6%96%87%e4%bb%b6) -->
<h1 id=""><a class="markdownIt-Anchor" href="#"></a> <a href="#%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83" title="开发环境"></a>开发环境</h1>
<h2 id="-2"><a class="markdownIt-Anchor" href="#-2"></a> <a href="#VSCode" title="VSCode"></a>VSCode</h2>
<p>window下需要安装<code>Clang</code>，百度找<code>Clang</code>，去官网自行下载，如果下载速度慢，可以添加以下内容到<code>C:\Windows\System32\drivers\etc\host</code>文件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">54.231.82.146 vagrantcloud-files-production.s3.amazonaws.com  </span><br><span class="line">219.76.4.4 s3.amazonaws.com  </span><br><span class="line">219.76.4.4 github-cloud.s3.amazonaws.com  </span><br></pre></td></tr></table></figure>
<p>然后再<code>VSCode</code>中安装两个插件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">vscode-proto3  </span><br><span class="line">Clang-Format  </span><br></pre></td></tr></table></figure>
<h1 id="-3"><a class="markdownIt-Anchor" href="#-3"></a> <a href="#%E6%B6%88%E6%81%AF%E7%B1%BB%E5%9E%8B%E7%9A%84%E6%BC%94%E8%BF%9B" title="消息类型的演进"></a>消息类型的演进</h1>
<ul>
<li>
<p>向前兼容变更：使用新的<code>.proto</code>文件来写数据 – 从旧的<code>.proto</code>文件读取数据</p>
</li>
<li>
<p>向后兼容变更：使用旧的<code>.proto</code>文件来写数据 – 从新的<code>.proto</code>文件读取数据</p>
<h2 id="-4"><a class="markdownIt-Anchor" href="#-4"></a> <a href="#%E6%9B%B4%E6%96%B0%E6%B6%88%E6%81%AF%E7%B1%BB%E5%9E%8B%E7%9A%84%E8%A7%84%E5%88%99" title="更新消息类型的规则"></a>更新消息类型的规则</h2>
</li>
<li>
<p>不要修改任何现有字段的数字(tag)</p>
</li>
<li>
<p>可以添加新的字段，旧的代码会忽略掉新字段的解析，所以要注意新字段的默认值</p>
</li>
<li>
<p>字段可以被删除，只要它们的数字<code>(tag)</code>在更新后的消息类型中不再使用即可，也可以把字段名使用<code>OBSOLETE_</code>前缀而不是删除字段，或者把这些字段的数字<code>(tag)</code>进行保留<code>(reserved)</code>，以免未来其他开发者不小心使用这些字段</p>
</li>
<li>
<p>尽量不要修改原有的字符数据类型</p>
<h2 id="-5"><a class="markdownIt-Anchor" href="#-5"></a> <a href="#%E9%BB%98%E8%AE%A4%E5%80%BC" title="默认值"></a>默认值</h2>
<p>默认值在更新<code>Protocol Buffer</code>消息定义的时候有很重要的作用，它可以防止对现有代码/新代码造成破坏性影响。它们也可以保证字段永远不会有<code>null</code>值</p>
</li>
</ul>
<p>但是，默认值还是非常危险的：<strong>你无法区分这个默认值到底是来自一个丢失的字段还是字段的实际值正好等于默认值</strong></p>
<p>所以，需要保证这个默认值对于业务来说是一个毫无意义的值，例如<code>int32 pop</code>人口这个字段的默认值可以设置为<code>-1</code>，再就是可能需要再代码里对默认值进行判断处理</p>
<h2 id="-6"><a class="markdownIt-Anchor" href="#-6"></a> <a href="#%E6%9E%9A%E4%B8%BE" title="枚举"></a>枚举</h2>
<p><code>enum</code>同样可以进化，就和消息的字段一样，可以添加、删除值，也可以保留值</p>
<p>但是如果代码不知道它接收到的值对应哪个<code>enum</code>值，那么<code>enum</code>的默认值将会被采用</p>
<h1 id="-7"><a class="markdownIt-Anchor" href="#-7"></a> <a href="#%E5%9C%A8-NET-Core%E4%B8%AD%E4%BD%BF%E7%94%A8gRPC" title="在.NET Core中使用gRPC"></a>在<code>.NET Core</code>中使用<code>gRPC</code></h1>
<h2 id="-8"><a class="markdownIt-Anchor" href="#-8"></a> <a href="#ASP-NET-Core" title="ASP.NET Core"></a><code>ASP.NET Core</code></h2>
<p>依赖包：</p>
<p><code>Grpc.AspNetCore </code></p>
<h2 id="-9"><a class="markdownIt-Anchor" href="#-9"></a> <a href="#NET-Core" title=".NET Core"></a><code>.NET Core</code></h2>
<p>依赖包：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Google.Protobuf  </span><br><span class="line">Grpc.Net.Client  </span><br><span class="line">Grpc.Tools  </span><br></pre></td></tr></table></figure>
<h2 id="-10"><a class="markdownIt-Anchor" href="#-10"></a> <a href="#%E5%BC%95%E5%8C%85%E4%B9%8B%E5%90%8E%E7%9A%84%E6%93%8D%E4%BD%9C" title="引包之后的操作"></a>引包之后的操作</h2>
<p>按照项目类型引入上面的包之后，直接编译是不会得到<code>gRPC</code>框架生成的代码，需要做以下操作：<br />
右键.proto文件 -&gt; 属性 -&gt; 将<code>Build Action</code>选择为<code>Protobuf compiler</code> -&gt; <code>gRPC Stub Classes</code>按照需求选择<code>Client and Server/Client only/Server only/Do not generate</code></p>
<p>进行完上面的操作之后，编译项目会在<code>obj\Debug\netcoreapp3.1</code>目录里自动生成<code>RPC</code>代码</p>
<h2 id="-11"><a class="markdownIt-Anchor" href="#-11"></a> <a href="#%E4%BD%9C%E4%B8%BA%E6%9C%8D%E5%8A%A1%E7%AB%AF" title="作为服务端"></a>作为服务端</h2>
<p>怎么实现<code>rpc</code>定义的方法：假设在<code>.proto</code>文件里有<code>EmployeeService</code>这样一个<code>service</code>，在编译项目之后，会有一个<code>EmployeeService.EmployeeServiceBase</code>的类，自己编写一个类继承自<code>EmployeeService.EmployeeServiceBase</code>这个类，然后<code>override</code>去重载<code>.proto</code>服务里定义的那些<code>rpc</code>方法即可</p>
<h2 id="-12"><a class="markdownIt-Anchor" href="#-12"></a> <a href="#%E4%BD%9C%E4%B8%BA%E5%AE%A2%E6%88%B7%E7%AB%AF" title="作为客户端"></a>作为客户端</h2>
<p>怎么调用<code>rpc</code>定义的方法：需要先创建<code>Channel</code>，例如：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> <span class="keyword">var</span> channel = GrpcChannel.ForAddress(<span class="string">&quot;https://localhost:5001&quot;</span>);  </span><br></pre></td></tr></table></figure>
<p>然后假设在<code>.proto</code>文件里有<code>EmployeeService</code>这样一个<code>service</code>，在编译项目之后(需要选择client或client and server)，会有一个<code>EmployeeService.EmployeeServiceClient</code>的类，实例化这个类就相当实例化一个<code>client</code>，例如：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> client = <span class="keyword">new</span> EmployeeService.EmployeeServiceClient(channel);  </span><br></pre></td></tr></table></figure>
<p>在<code>client</code>里就可以调用<code>.proto</code>服务里定义的那些方法</p>
<h1 id="-13"><a class="markdownIt-Anchor" href="#-13"></a> <a href="#%E4%B8%8A%E4%BB%A3%E7%A0%81" title="上代码"></a>上代码</h1>
<h2 id="-14"><a class="markdownIt-Anchor" href="#-14"></a> <a href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF" title="服务端"></a>服务端</h2>
<p>创建名字为<code>RoutingDemo</code>的<code>ASP.NET Core</code>项目，类型为<code>空</code>，通过<code>nuget</code>引入：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Grpc.AspNetCore  </span><br></pre></td></tr></table></figure>
<h3 id="-15"><a class="markdownIt-Anchor" href="#-15"></a> <a href="#%E5%88%9B%E5%BB%BA%E7%9B%AE%E5%BD%95" title="创建目录"></a>创建目录</h3>
<p>在项目根目录创建以下三个文件夹</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Data  </span><br><span class="line">Protos  </span><br><span class="line">Services  </span><br></pre></td></tr></table></figure>
<h3 id="-16"><a class="markdownIt-Anchor" href="#-16"></a> <a href="#%E7%BC%96%E5%86%99proto" title="编写proto"></a>编写<code>proto</code></h3>
<p>在<code>Protos</code>文件夹中添加文件<code>Order.proto</code>，具体内容如下：</p>
<figure class="highlight proto"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">syntax = <span class="string">&quot;proto3&quot;</span>;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">option</span> csharp_namespace = <span class="string">&quot;GrpcDemo.Protos&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">message </span><span class="title class_">Order</span>&#123;  </span><br><span class="line">	<span class="type">int32</span> Id = <span class="number">1</span>;  </span><br><span class="line">	<span class="type">string</span> OrderNo = <span class="number">2</span>;  </span><br><span class="line">	<span class="type">int32</span> Status = <span class="number">3</span>;  </span><br><span class="line">	<span class="type">float</span> Payment = <span class="number">4</span>;  </span><br><span class="line">	<span class="keyword">repeated</span> OrderProduct Products = <span class="number">5</span>;  </span><br><span class="line">	OrderAddress Address = <span class="number">6</span>;  </span><br><span class="line">	<span class="type">int32</span> OrderOwner = <span class="number">7</span>;  </span><br><span class="line">  </span><br><span class="line">	<span class="keyword">message </span><span class="title class_">OrderProduct</span>&#123;  </span><br><span class="line">		<span class="type">string</span> ProductTitle = <span class="number">1</span>;  </span><br><span class="line">		<span class="type">string</span> SkuTitle = <span class="number">2</span>;  </span><br><span class="line">		<span class="type">int32</span> Num = <span class="number">3</span>;  </span><br><span class="line">		<span class="type">float</span> UnitPrice = <span class="number">4</span>;  </span><br><span class="line">	&#125;  </span><br><span class="line">  </span><br><span class="line">	<span class="keyword">message </span><span class="title class_">OrderAddress</span>&#123;  </span><br><span class="line">		<span class="type">string</span> Province = <span class="number">1</span>;  </span><br><span class="line">		<span class="type">string</span> City = <span class="number">2</span>;  </span><br><span class="line">		<span class="type">string</span> Districe = <span class="number">3</span>;  </span><br><span class="line">		<span class="type">string</span> Detail = <span class="number">4</span>;  </span><br><span class="line">		<span class="type">string</span> Name = <span class="number">5</span>;  </span><br><span class="line">		<span class="type">string</span> Mobile = <span class="number">6</span>;  </span><br><span class="line">	&#125;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">message </span><span class="title class_">GetByOrderNoRequest</span>&#123;  </span><br><span class="line">	<span class="type">string</span> OrderNo = <span class="number">1</span>;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">message </span><span class="title class_">GetByOwnerRequest</span>&#123;  </span><br><span class="line">	<span class="type">int32</span> OrderOwner = <span class="number">1</span>;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">message </span><span class="title class_">BatchAddOrderNoReturnResponse</span>&#123;  </span><br><span class="line">	<span class="type">bool</span> IsAllSuccess = <span class="number">1</span>;  </span><br><span class="line">	<span class="keyword">repeated</span> <span class="type">string</span> FailOrderNo = <span class="number">2</span>;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">service </span><span class="title class_">OrderService</span>&#123;  </span><br><span class="line">	<span class="function"><span class="keyword">rpc</span> GetByOrderNo(GetByOrderNoRequest) <span class="keyword">returns</span>(Order)</span>;  </span><br><span class="line">	<span class="function"><span class="keyword">rpc</span> GetByOwner(GetByOwnerRequest) <span class="keyword">returns</span>(stream Order)</span>;  </span><br><span class="line">	<span class="function"><span class="keyword">rpc</span> AddOrder(Order) <span class="keyword">returns</span>(Order)</span>;  </span><br><span class="line">	<span class="function"><span class="keyword">rpc</span> BatchAddOrder(stream Order) <span class="keyword">returns</span>(stream Order)</span>;  </span><br><span class="line">	<span class="function"><span class="keyword">rpc</span> BatchAddOrderNoReturn(stream Order) <span class="keyword">returns</span>(BatchAddOrderNoReturnResponse)</span>;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p>在<code>解决方案资源管理器</code>找到<code>Order.proto</code>文件，右键 -&gt; 属性 -&gt; <code>Build Action</code>选择<code>Protobuf compiler</code> -&gt; <code>gRPC Stub Classes</code>选择<code>Server only</code></p>
<p>编译一次项目</p>
<h3 id="-17"><a class="markdownIt-Anchor" href="#-17"></a> <a href="#%E7%BC%96%E5%86%99%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE" title="编写测试数据"></a>编写测试数据</h3>
<p>在<code>Data</code>文件夹创建<code>InMemoryData.cs</code>文件，内容如下：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System.Collections.Generic;  </span><br><span class="line"><span class="keyword">using</span> GrpcDemo.Protos;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">GrpcServerDemo.Data</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">InMemoryData</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">static</span> List&lt;Order&gt; Orders = <span class="keyword">new</span> List&lt;Order&gt;()  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">new</span> Order()  </span><br><span class="line">            &#123;  </span><br><span class="line">                Id = <span class="number">1</span>,  </span><br><span class="line">                OrderNo = <span class="string">&quot;2020042201&quot;</span>,  </span><br><span class="line">                Status = <span class="number">1</span>,  </span><br><span class="line">                Payment = <span class="number">43141.98f</span>,  </span><br><span class="line">                Products =  </span><br><span class="line">                &#123;  </span><br><span class="line">                    <span class="keyword">new</span> Order.Types.OrderProduct()  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        ProductTitle = <span class="string">&quot;Apple iPhone11&quot;</span>,  </span><br><span class="line">                        SkuTitle = <span class="string">&quot;256GB 黑色&quot;</span>,  </span><br><span class="line">                        Num = <span class="number">2</span>,  </span><br><span class="line">                        UnitPrice = <span class="number">9999.99f</span>  </span><br><span class="line">                    &#125;,  </span><br><span class="line">                    <span class="keyword">new</span> Order.Types.OrderProduct()  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        ProductTitle = <span class="string">&quot;Apple MacBook Pro&quot;</span>,  </span><br><span class="line">                        SkuTitle = <span class="string">&quot;i7 512GB 灰色&quot;</span>,  </span><br><span class="line">                        Num = <span class="number">1</span>,  </span><br><span class="line">                        UnitPrice = <span class="number">23142</span>  </span><br><span class="line">                    &#125;  </span><br><span class="line">                &#125;,  </span><br><span class="line">                Address = <span class="keyword">new</span> Order.Types.OrderAddress()  </span><br><span class="line">                &#123;  </span><br><span class="line">                    Province = <span class="string">&quot;广东省&quot;</span>,  </span><br><span class="line">                    City = <span class="string">&quot;深圳市&quot;</span>,  </span><br><span class="line">                    Districe = <span class="string">&quot;南山区&quot;</span>,  </span><br><span class="line">                    Detail = <span class="string">&quot;Nanshan Road 1234&quot;</span>,  </span><br><span class="line">                    Name = <span class="string">&quot;Jiamiao.x&quot;</span>,  </span><br><span class="line">                    Mobile = <span class="string">&quot;13500000000&quot;</span>  </span><br><span class="line">                &#125;,  </span><br><span class="line">                OrderOwner = <span class="number">100</span>,  </span><br><span class="line">            &#125;,  </span><br><span class="line">            <span class="keyword">new</span> Order()  </span><br><span class="line">            &#123;  </span><br><span class="line">                Id = <span class="number">2</span>,  </span><br><span class="line">                OrderNo = <span class="string">&quot;2020042202&quot;</span>,  </span><br><span class="line">                Status = <span class="number">2</span>,  </span><br><span class="line">                Payment = <span class="number">56.00f</span>,  </span><br><span class="line">                Products =  </span><br><span class="line">                &#123;  </span><br><span class="line">                    <span class="keyword">new</span> Order.Types.OrderProduct()  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        ProductTitle = <span class="string">&quot;ASP.NET Core微服务实战&quot;</span>,  </span><br><span class="line">                        SkuTitle = <span class="string">&quot;1本&quot;</span>,  </span><br><span class="line">                        Num = <span class="number">1</span>,  </span><br><span class="line">                        UnitPrice = <span class="number">56.00f</span>  </span><br><span class="line">                    &#125;  </span><br><span class="line">                &#125;,  </span><br><span class="line">                Address = <span class="keyword">new</span> Order.Types.OrderAddress()  </span><br><span class="line">                &#123;  </span><br><span class="line">                    Province = <span class="string">&quot;广东省&quot;</span>,  </span><br><span class="line">                    City = <span class="string">&quot;深圳市&quot;</span>,  </span><br><span class="line">                    Districe = <span class="string">&quot;南山区&quot;</span>,  </span><br><span class="line">                    Detail = <span class="string">&quot;Nanshan Road 1234&quot;</span>,  </span><br><span class="line">                    Name = <span class="string">&quot;Jiamiao.x&quot;</span>,  </span><br><span class="line">                    Mobile = <span class="string">&quot;13500000000&quot;</span>  </span><br><span class="line">                &#125;,  </span><br><span class="line">                OrderOwner = <span class="number">100</span>  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p><strong>注意：这里的<code>Order</code>是<code>gRPC</code>生成的，命名空间为<code>GrpcDemo.Protos</code></strong></p>
<h3 id="-18"><a class="markdownIt-Anchor" href="#-18"></a> <a href="#%E7%BC%96%E5%86%99Service" title="编写Service"></a>编写<code>Service</code></h3>
<p>在<code>Services</code>文件夹创建<code>DemoOrderService.cs</code>文件，内容如下：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Linq;  </span><br><span class="line"><span class="keyword">using</span> System.Threading;  </span><br><span class="line"><span class="keyword">using</span> System.Threading.Tasks;  </span><br><span class="line"><span class="keyword">using</span> Grpc.Core;  </span><br><span class="line"><span class="keyword">using</span> GrpcDemo.Protos;  </span><br><span class="line"><span class="keyword">using</span> GrpcServerDemo.Data;  </span><br><span class="line"><span class="keyword">using</span> Microsoft.Extensions.Logging;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">GrpcServerDemo.Services</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">DemoOrderService</span> : <span class="title">OrderService.OrderServiceBase</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">readonly</span> ILogger&lt;DemoOrderService&gt; _logger;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">DemoOrderService</span>(<span class="params">ILogger&lt;DemoOrderService&gt; logger</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _logger = logger;  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">async</span> Task&lt;Order&gt; <span class="title">GetByOrderNo</span>(<span class="params">GetByOrderNoRequest request, ServerCallContext context</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _logger.LogInformation(<span class="string">&quot;有人请求接口 -&gt; GetByOrderNo&quot;</span>);  </span><br><span class="line">            <span class="keyword">var</span> metaData = context.RequestHeaders;  </span><br><span class="line">            <span class="keyword">foreach</span> (<span class="keyword">var</span> item <span class="keyword">in</span> metaData)  </span><br><span class="line">            &#123;  </span><br><span class="line">                _logger.LogInformation(<span class="string">$&quot;<span class="subst">&#123;item.Key&#125;</span>: <span class="subst">&#123;item.Value&#125;</span>&quot;</span>);  </span><br><span class="line">            &#125;  </span><br><span class="line">            <span class="keyword">await</span> Task.CompletedTask;  </span><br><span class="line">            <span class="keyword">var</span> dbValue = InMemoryData.Orders.FirstOrDefault(x =&gt; x.OrderNo == request.OrderNo);  </span><br><span class="line">            <span class="keyword">if</span> (dbValue != <span class="literal">null</span>)  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">return</span> dbValue;  </span><br><span class="line">            &#125;  </span><br><span class="line">            <span class="keyword">else</span>  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">throw</span>  <span class="keyword">new</span> Exception(<span class="string">&quot;订单号错误&quot;</span>);  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">async</span> Task <span class="title">GetByOwner</span>(<span class="params">GetByOwnerRequest request, IServerStreamWriter&lt;Order&gt; responseStream, ServerCallContext context</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _logger.LogInformation(<span class="string">&quot;有人请求接口 -&gt; GetByOwner&quot;</span>);  </span><br><span class="line">            <span class="keyword">var</span> dbValue = InMemoryData.Orders.Where(x =&gt; x.OrderOwner == request.OrderOwner);  </span><br><span class="line">            <span class="keyword">foreach</span> (<span class="keyword">var</span> item <span class="keyword">in</span> dbValue)  </span><br><span class="line">            &#123;  </span><br><span class="line">                Thread.Sleep(<span class="number">2000</span>);  </span><br><span class="line">                _logger.LogInformation(<span class="string">$&quot;发送数据：<span class="subst">&#123;item&#125;</span>&quot;</span>);  </span><br><span class="line">                <span class="keyword">await</span> responseStream.WriteAsync(item);  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">async</span> Task&lt;Order&gt; <span class="title">AddOrder</span>(<span class="params">Order request, ServerCallContext context</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _logger.LogInformation(<span class="string">&quot;有人请求接口 -&gt; AddOrder&quot;</span>);  </span><br><span class="line">            <span class="keyword">await</span> Task.CompletedTask;  </span><br><span class="line">            request.Id = InMemoryData.Orders.Max(x =&gt; x.Id) + <span class="number">1</span>;  </span><br><span class="line">            InMemoryData.Orders.Add(request);  </span><br><span class="line">            <span class="keyword">return</span> request;  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">async</span> Task <span class="title">BatchAddOrder</span>(<span class="params">IAsyncStreamReader&lt;Order&gt; requestStream, IServerStreamWriter&lt;Order&gt; responseStream, ServerCallContext context</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _logger.LogInformation(<span class="string">&quot;有人请求接口 -&gt; BatchAddOrder&quot;</span>);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">await</span> requestStream.MoveNext())  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">var</span> inputOrder = requestStream.Current;  </span><br><span class="line">                <span class="keyword">lock</span> (<span class="keyword">this</span>)  </span><br><span class="line">                &#123;  </span><br><span class="line">                    _logger.LogInformation(<span class="string">$&quot;接受数据：<span class="subst">&#123;inputOrder&#125;</span>&quot;</span>);  </span><br><span class="line">                    inputOrder.Id = InMemoryData.Orders.Max(x =&gt; x.Id) + <span class="number">1</span>;  </span><br><span class="line">                    InMemoryData.Orders.Add(inputOrder);  </span><br><span class="line">                &#125;  </span><br><span class="line">                <span class="keyword">await</span> responseStream.WriteAsync(inputOrder);  </span><br><span class="line">                Thread.Sleep(<span class="number">5000</span>);  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p><strong>注意：这里的<code>OrderService.OrderServiceBase</code>一样是<code>gRPC</code>生成的，命名空间为<code>GrpcDemo.Protos</code></strong></p>
<h3 id="-19"><a class="markdownIt-Anchor" href="#-19"></a> <a href="#%E4%BF%AE%E6%94%B9Startup" title="修改Startup"></a>修改<code>Startup</code></h3>
<p>修改<code>Startup.cs</code>，内容如下：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> GrpcServerDemo.Services;  </span><br><span class="line"><span class="keyword">using</span> Microsoft.AspNetCore.Builder;  </span><br><span class="line"><span class="keyword">using</span> Microsoft.AspNetCore.Hosting;  </span><br><span class="line"><span class="keyword">using</span> Microsoft.Extensions.DependencyInjection;  </span><br><span class="line"><span class="keyword">using</span> Microsoft.Extensions.Hosting;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">GrpcServerDemo</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Startup</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ConfigureServices</span>(<span class="params">IServiceCollection services</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            services.AddGrpc();  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Configure</span>(<span class="params">IApplicationBuilder app, IWebHostEnvironment env</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">if</span> (env.IsDevelopment())  </span><br><span class="line">            &#123;  </span><br><span class="line">                app.UseDeveloperExceptionPage();  </span><br><span class="line">            &#125;  </span><br><span class="line">  </span><br><span class="line">            app.UseHttpsRedirection();  </span><br><span class="line">            app.UseRouting();  </span><br><span class="line">  </span><br><span class="line">            app.UseEndpoints(endpoints =&gt;  </span><br><span class="line">            &#123;  </span><br><span class="line">                endpoints.MapGrpcService&lt;DemoOrderService&gt;();  </span><br><span class="line">            &#125;);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<h3 id="-20"><a class="markdownIt-Anchor" href="#-20"></a> <a href="#%E8%BF%90%E8%A1%8C%E9%A1%B9%E7%9B%AE" title="运行项目"></a>运行项目</h3>
<p>在<code>Powershell</code>中进入到项目根目录，直接<code>dotnet run</code>运行目录即可</p>
<h2 id="-21"><a class="markdownIt-Anchor" href="#-21"></a> <a href="#%E5%AE%A2%E6%88%B7%E7%AB%AF" title="客户端"></a>客户端</h2>
<h3 id="-22"><a class="markdownIt-Anchor" href="#-22"></a> <a href="#%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE" title="创建项目"></a>创建项目</h3>
<p>创建名字为<code>GrpcClientDemo</code>的<code>控制台应用</code>，通过<code>nuget</code>引入以下三个包：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Google.Protobuf  </span><br><span class="line">Grpc.Net.Client  </span><br><span class="line">Grpc.Tools  </span><br></pre></td></tr></table></figure>
<h3 id="-23"><a class="markdownIt-Anchor" href="#-23"></a> <a href="#%E5%A4%8D%E5%88%B6proto%E6%96%87%E4%BB%B6" title="复制proto文件"></a>复制<code>proto</code>文件</h3>
<p>将服务端<code>GrpcServerDemo</code>的<code>Protos</code>文件夹拷贝到项目根目录，在<code>解决方案资源管理器</code>找到<code>Order.proto</code>文件，右键 -&gt; 属性 -&gt; <code>Build Action</code>选择<code>Protobuf compiler</code> -&gt; <code>gRPC Stub Classes</code>选择<code>Client only</code></p>
<h3 id="-24"><a class="markdownIt-Anchor" href="#-24"></a> <a href="#%E4%BF%AE%E6%94%B9Program-cs" title="修改Program.cs"></a>修改<code>Program.cs</code></h3>
<p>修改<code>Program.cs</code>文件，内容如下：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Collections.Generic;  </span><br><span class="line"><span class="keyword">using</span> System.Threading.Tasks;  </span><br><span class="line"><span class="keyword">using</span> Grpc.Core;  </span><br><span class="line"><span class="keyword">using</span> Grpc.Net.Client;  </span><br><span class="line"><span class="keyword">using</span> GrpcDemo.Protos;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">GrpcClientDemo</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">async</span> Task <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>\[\] args</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> channel = GrpcChannel.ForAddress(<span class="string">&quot;https://localhost:5001&quot;</span>);  </span><br><span class="line">            <span class="keyword">var</span> client = <span class="keyword">new</span> OrderService.OrderServiceClient(channel);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> option = <span class="built_in">int</span>.Parse(args\[<span class="number">0</span>\]);  </span><br><span class="line">            <span class="keyword">switch</span> (option)  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">case</span> <span class="number">0</span>:  </span><br><span class="line">                    <span class="keyword">await</span> GetByOrderNoAsync(client);  </span><br><span class="line">                    <span class="keyword">break</span>;  </span><br><span class="line">                <span class="keyword">case</span> <span class="number">1</span>:  </span><br><span class="line">                    <span class="keyword">await</span> GetByOwner(client);  </span><br><span class="line">                    <span class="keyword">break</span>;  </span><br><span class="line">                <span class="keyword">case</span> <span class="number">2</span>:  </span><br><span class="line">                    <span class="keyword">await</span> AddOrder(client);  </span><br><span class="line">                    <span class="keyword">break</span>;  </span><br><span class="line">                <span class="keyword">case</span> <span class="number">3</span>:  </span><br><span class="line">                    <span class="keyword">await</span> BatchAddOrder(client);  </span><br><span class="line">                    <span class="keyword">break</span>;  </span><br><span class="line">            &#125;  </span><br><span class="line">  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;==========END==========&quot;</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">async</span> Task <span class="title">GetByOrderNoAsync</span>(<span class="params">OrderService.OrderServiceClient client</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">var</span> metaData = <span class="keyword">new</span> Metadata()  </span><br><span class="line">            &#123;  </span><br><span class="line">                &#123;<span class="string">&quot;userName&quot;</span>, <span class="string">&quot;jiamiao.x&quot;</span>&#125;,  </span><br><span class="line">                &#123;<span class="string">&quot;clientName&quot;</span>, <span class="string">&quot;GrpcClientDemo&quot;</span>&#125;  </span><br><span class="line">            &#125;;  </span><br><span class="line">            <span class="keyword">var</span> response = <span class="keyword">await</span> client.GetByOrderNoAsync(<span class="keyword">new</span> GetByOrderNoRequest() &#123;OrderNo = <span class="string">&quot;2020042201&quot;</span>&#125;,metaData);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;接收到数据：<span class="subst">&#123;response&#125;</span>&quot;</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">async</span> Task <span class="title">GetByOwner</span>(<span class="params">OrderService.OrderServiceClient client</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">var</span> response = client.GetByOwner(<span class="keyword">new</span> GetByOwnerRequest() &#123;OrderOwner = <span class="number">100</span>&#125;);  </span><br><span class="line">            <span class="keyword">var</span> responseStream = response.ResponseStream;  </span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">await</span> responseStream.MoveNext())  </span><br><span class="line">            &#123;  </span><br><span class="line">                Console.WriteLine(<span class="string">$&quot;接收到数据：<span class="subst">&#123;responseStream.Current&#125;</span>&quot;</span>);  </span><br><span class="line">            &#125;  </span><br><span class="line">  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;数据接收完毕&quot;</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">async</span> Task <span class="title">AddOrder</span>(<span class="params">OrderService.OrderServiceClient client</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">var</span> order = <span class="keyword">new</span> Order()  </span><br><span class="line">            &#123;  </span><br><span class="line">                OrderNo = <span class="string">&quot;2020042301&quot;</span>,  </span><br><span class="line">                Status = <span class="number">1</span>,  </span><br><span class="line">                Payment = <span class="number">43141.98f</span>,  </span><br><span class="line">                Products =  </span><br><span class="line">                &#123;  </span><br><span class="line">                    <span class="keyword">new</span> Order.Types.OrderProduct()  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        ProductTitle = <span class="string">&quot;OnePlus 7T&quot;</span>,  </span><br><span class="line">                        SkuTitle = <span class="string">&quot;256GB 蓝色&quot;</span>,  </span><br><span class="line">                        Num = <span class="number">1</span>,  </span><br><span class="line">                        UnitPrice = <span class="number">3600f</span>  </span><br><span class="line">                    &#125;  </span><br><span class="line">                &#125;,  </span><br><span class="line">                Address = <span class="keyword">new</span> Order.Types.OrderAddress()  </span><br><span class="line">                &#123;  </span><br><span class="line">                    Province = <span class="string">&quot;广东省&quot;</span>,  </span><br><span class="line">                    City = <span class="string">&quot;深圳市&quot;</span>,  </span><br><span class="line">                    Districe = <span class="string">&quot;南山区&quot;</span>,  </span><br><span class="line">                    Detail = <span class="string">&quot;北科大厦7003&quot;</span>,  </span><br><span class="line">                    Name = <span class="string">&quot;Jiamiao.x&quot;</span>,  </span><br><span class="line">                    Mobile = <span class="string">&quot;13822113366&quot;</span>  </span><br><span class="line">                &#125;,  </span><br><span class="line">                OrderOwner = <span class="number">100</span>,  </span><br><span class="line">            &#125;;  </span><br><span class="line">            <span class="keyword">var</span> response = <span class="keyword">await</span> client.AddOrderAsync(order);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;接收到数据：<span class="subst">&#123;response&#125;</span>&quot;</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">async</span> Task <span class="title">BatchAddOrder</span>(<span class="params">OrderService.OrderServiceClient client</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">var</span> orders = <span class="keyword">new</span> List&lt;Order&gt;()  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">new</span> Order()  </span><br><span class="line">                &#123;  </span><br><span class="line">                    OrderNo = <span class="string">&quot;2020042301&quot;</span>,  </span><br><span class="line">                    Status = <span class="number">1</span>,  </span><br><span class="line">                    Payment = <span class="number">3600f</span>,  </span><br><span class="line">                    Products =  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        <span class="keyword">new</span> Order.Types.OrderProduct()  </span><br><span class="line">                        &#123;  </span><br><span class="line">                            ProductTitle = <span class="string">&quot;OnePlus 7T&quot;</span>,  </span><br><span class="line">                            SkuTitle = <span class="string">&quot;256GB 蓝色&quot;</span>,  </span><br><span class="line">                            Num = <span class="number">1</span>,  </span><br><span class="line">                            UnitPrice = <span class="number">3600f</span>  </span><br><span class="line">                        &#125;  </span><br><span class="line">                    &#125;,  </span><br><span class="line">                    Address = <span class="keyword">new</span> Order.Types.OrderAddress()  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        Province = <span class="string">&quot;广东省&quot;</span>,  </span><br><span class="line">                        City = <span class="string">&quot;深圳市&quot;</span>,  </span><br><span class="line">                        Districe = <span class="string">&quot;南山区&quot;</span>,  </span><br><span class="line">                        Detail = <span class="string">&quot;北科大厦7003&quot;</span>,  </span><br><span class="line">                        Name = <span class="string">&quot;Jiamiao.x&quot;</span>,  </span><br><span class="line">                        Mobile = <span class="string">&quot;13822113366&quot;</span>  </span><br><span class="line">                    &#125;,  </span><br><span class="line">                    OrderOwner = <span class="number">100</span>,  </span><br><span class="line">                &#125;,  </span><br><span class="line">                <span class="keyword">new</span> Order()  </span><br><span class="line">                &#123;  </span><br><span class="line">                    OrderNo = <span class="string">&quot;2020042302&quot;</span>,  </span><br><span class="line">                    Status = <span class="number">1</span>,  </span><br><span class="line">                    Payment = <span class="number">13999.99f</span>,  </span><br><span class="line">                    Products =  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        <span class="keyword">new</span> Order.Types.OrderProduct()  </span><br><span class="line">                        &#123;  </span><br><span class="line">                            ProductTitle = <span class="string">&quot;SONY PS4 Pro&quot;</span>,  </span><br><span class="line">                            SkuTitle = <span class="string">&quot;1TB 黑色&quot;</span>,  </span><br><span class="line">                            Num = <span class="number">1</span>,  </span><br><span class="line">                            UnitPrice = <span class="number">3999.99f</span>  </span><br><span class="line">                        &#125;,  </span><br><span class="line">                        <span class="keyword">new</span> Order.Types.OrderProduct()  </span><br><span class="line">                        &#123;  </span><br><span class="line">                            ProductTitle = <span class="string">&quot;Surface Desktop Pro&quot;</span>,  </span><br><span class="line">                            SkuTitle = <span class="string">&quot;1TB 白色&quot;</span>,  </span><br><span class="line">                            Num = <span class="number">1</span>,  </span><br><span class="line">                            UnitPrice = <span class="number">13999.99f</span>  </span><br><span class="line">                        &#125;  </span><br><span class="line">                    &#125;,  </span><br><span class="line">                    Address = <span class="keyword">new</span> Order.Types.OrderAddress()  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        Province = <span class="string">&quot;广东省&quot;</span>,  </span><br><span class="line">                        City = <span class="string">&quot;深圳市&quot;</span>,  </span><br><span class="line">                        Districe = <span class="string">&quot;南山区&quot;</span>,  </span><br><span class="line">                        Detail = <span class="string">&quot;北科大厦7003&quot;</span>,  </span><br><span class="line">                        Name = <span class="string">&quot;Jiamiao.x&quot;</span>,  </span><br><span class="line">                        Mobile = <span class="string">&quot;13822113366&quot;</span>  </span><br><span class="line">                    &#125;,  </span><br><span class="line">                    OrderOwner = <span class="number">100</span>,  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;;  </span><br><span class="line">            <span class="keyword">var</span> call = client.BatchAddOrder();  </span><br><span class="line">              </span><br><span class="line">            <span class="keyword">foreach</span> (<span class="keyword">var</span> order <span class="keyword">in</span> orders)  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">await</span> call.RequestStream.WriteAsync(order);  </span><br><span class="line">            &#125;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">await</span> call.RequestStream.CompleteAsync();  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;----数据发送完毕----&quot;</span>);  </span><br><span class="line">            <span class="keyword">await</span> Task.Run(<span class="keyword">async</span> () =&gt;  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">while</span> (<span class="keyword">await</span> call.ResponseStream.MoveNext())  </span><br><span class="line">                &#123;  </span><br><span class="line">                    Console.WriteLine(<span class="string">$&quot;接收到消息：<span class="subst">&#123;call.ResponseStream.Current&#125;</span>&quot;</span>);  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<h3 id="-25"><a class="markdownIt-Anchor" href="#-25"></a> <a href="#%E8%BF%90%E8%A1%8C%E9%A1%B9%E7%9B%AE-1" title="运行项目"></a>运行项目</h3>
<p>在<code>Powershell</code>进入到项目根目录，使用<code>dotnet run [arg]</code>运行项目既可以看到效果，<code>[arg]</code>是对应<code>switch</code>里的参数</p>
<h1 id="-26"><a class="markdownIt-Anchor" href="#-26"></a> <a href="#%E6%97%A5%E5%BF%97%E5%92%8C%E5%BC%82%E5%B8%B8" title="日志和异常"></a>日志和异常</h1>
<h2 id="-27"><a class="markdownIt-Anchor" href="#-27"></a> <a href="#%E6%97%A5%E5%BF%97" title="日志"></a>日志</h2>
<h3 id="-28"><a class="markdownIt-Anchor" href="#-28"></a> <a href="#ASP-NET-Core-1" title="ASP.NET Core"></a><span class="exturl" data-url="aHR0cDovL0FTUC5ORVQ=">ASP.NET<i class="fa fa-external-link-alt"></i></span> Core</h3>
<p>作为服务端在<code>ASP.NET Core</code>中开启<code>gRPC</code>日志只需要在<code>appsettings.json</code>中配置<code>grpc</code>的日志等级即可，修改<code>appsettings.json</code>内容如下：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&#123;  </span><br><span class="line">  <span class="string">&quot;Logging&quot;</span>: &#123;  </span><br><span class="line">    <span class="string">&quot;LogLevel&quot;</span>: &#123;  </span><br><span class="line">      <span class="string">&quot;Default&quot;</span>: <span class="string">&quot;Information&quot;</span>,  </span><br><span class="line">      <span class="string">&quot;Microsoft&quot;</span>: <span class="string">&quot;Warning&quot;</span>,  </span><br><span class="line">      <span class="string">&quot;Microsoft.Hosting.Lifetime&quot;</span>: <span class="string">&quot;Information&quot;</span>,  </span><br><span class="line">      <span class="string">&quot;grpc&quot;</span>: <span class="string">&quot;Debug&quot;</span>   </span><br><span class="line">    &#125;  </span><br><span class="line">  &#125;,  </span><br><span class="line">  <span class="string">&quot;AllowedHosts&quot;</span>: <span class="string">&quot;\*&quot;</span>  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p>运行项目就可以看到控制台打印出<code>gRPC</code>相关日志</p>
<h3 id="-29"><a class="markdownIt-Anchor" href="#-29"></a> <a href="#NET-Core%E6%8E%A7%E5%88%B6%E5%8F%B0" title=".NET Core控制台"></a>.NET Core控制台</h3>
<p>在客户端的<code>.NET Core控制台程序</code>，需要自定义一个<code>LoggerFactory</code>，然后在创建<code>Channel</code>的时候指定自定义的<code>LoggerFactory</code>。这里的示例使用<code>Serilog</code>来作为日志组件，需要在引入以下三个包：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Serilog  </span><br><span class="line">Serilog.Extensions.Logging  </span><br><span class="line">Serilog.Sinks.Console  </span><br></pre></td></tr></table></figure>
<p>创建<code>SerilogLoggerFactory.cs</code>，内容如下：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> Microsoft.Extensions.Logging;  </span><br><span class="line"><span class="keyword">using</span> Serilog.Debugging;  </span><br><span class="line"><span class="keyword">using</span> Serilog.Extensions.Logging;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">Jiamiao.x.GrpcClient</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">SerilogLoggerFactory</span>:<span class="title">ILoggerFactory</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">readonly</span> SerilogLoggerProvider _provider;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">SerilogLoggerFactory</span>(<span class="params">Serilog.ILogger logger=<span class="literal">null</span>,<span class="built_in">bool</span> dispose = <span class="literal">false</span></span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _provider = <span class="keyword">new</span> SerilogLoggerProvider(logger, dispose);  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Dispose</span>()</span> =&gt; _provider.Dispose();  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> ILogger <span class="title">CreateLogger</span>(<span class="params"><span class="built_in">string</span> categoryName</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">return</span> _provider.CreateLogger(categoryName);  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">AddProvider</span>(<span class="params">ILoggerProvider provider</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            SelfLog.WriteLine(<span class="string">&quot;Ignore added logger provider &#123;0&#125;&quot;</span>, provider);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p>回到<code>gRPC</code>服务调用的地方，将创建<code>GrpcChannel</code>的代码修改如下：</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> <span class="keyword">var</span> channel = GrpcChannel.ForAddress(<span class="string">&quot;https://localhost:5001&quot;</span>,<span class="keyword">new</span> GrpcChannelOptions()  </span><br><span class="line">&#123;  </span><br><span class="line">    LoggerFactory = <span class="keyword">new</span> SerilogLoggerFactory()  </span><br><span class="line">&#125;);  </span><br></pre></td></tr></table></figure>
<p>运行项目即可以看到<code>gRPC</code>日志内容</p>
<h2 id="-30"><a class="markdownIt-Anchor" href="#-30"></a> <a href="#%E5%BC%82%E5%B8%B8" title="异常"></a>异常</h2>
<p>服务端在<code>gRPC</code>抛出异常的时候，可以抛出<code>RpcException</code>来指定异常类型，<code>RpcException</code>示例里的<code>trailer</code>是一个<code>Metadata</code>，可以携带自定义的键值对，客户端捕获异常也可以捕获指定的<code>RpcException</code>，一样可以拿到<code>trailer</code>来获取自定义的键值对信息</p>
<h1 id="-31"><a class="markdownIt-Anchor" href="#-31"></a> <a href="#%E5%85%B3%E4%BA%8EJWT%E6%8E%88%E6%9D%83" title="关于JWT授权"></a>关于JWT授权</h1>
<p>在通过授权接口获取到<code>JWT Token</code>之后，与普通<code>HTTP</code>请求类似，<code>JWT Token</code>也是放在头部与请求一起发送出去，只不过在<code>RPC</code>换了个名词，编程<code>MetaData</code>，其实是一样道理，用<code>Authorization:Bearer &#123;JWT Token&#125;</code>来进行发送即可</p>
<h1 id="-32"><a class="markdownIt-Anchor" href="#-32"></a> <a href="#%E5%A4%9A%E9%A1%B9%E7%9B%AE%E4%B9%8B%E9%97%B4%E5%85%B1%E4%BA%ABproto%E6%96%87%E4%BB%B6" title="多项目之间共享proto文件"></a>多项目之间共享<code>proto</code>文件</h1>
<ul>
<li>使用单独的<code>Git</code>仓库管理<code>proto</code>文件</li>
<li>使用<code>submodule</code>将<code>proto</code>文件集成到工程目录中</li>
<li>使用<code>dotnet-grpc</code>命令行添加<code>proto</code>文件及祥光依赖包引用</li>
</ul>
<p><em>备注：由<code>proto</code>生成的代码文件会存放在<code>obj</code>目录中，不会被嵌入到<code>Git</code>仓库</em></p>

    </div>

    
    
    

    <footer class="post-footer">







<div class="license">
  <div class="license-title">gRPC in ASP.NET Core</div>
  <div class="license-link">
    <a href="https://blog.fantasyke.cn/posts/34332/">https://blog.fantasyke.cn/posts/34332/</a>
  </div>
  <div class="license-meta">
    <div class="license-meta-item">
      <div class="license-meta-title">本文作者</div>
      <div class="license-meta-text">
          Fantasy-ke
      </div>
    </div>
      <div class="license-meta-item">
        <div class="license-meta-title">发布于</div>
        <div class="license-meta-text">
          2023-06-28
        </div>
      </div>
      <div class="license-meta-item">
        <div class="license-meta-title">更新于</div>
        <div class="license-meta-text">
          2024-12-17
        </div>
      </div>
    <div class="license-meta-item">
      <div class="license-meta-title">许可协议</div>
      <div class="license-meta-text">
          禁止转载引用
      </div>
    </div>
  </div>
  <div class="license-statement">
      如需转载或引用本文，请先获得作者授权！
  </div>
</div>
          <div class="reward-container">
  <div>Buy me a coffee</div>
  <button>
    Donate
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.png" alt="Fantasy-ke WeChat Pay">
        <span>WeChat Pay</span>
      </div>

  </div>
</div>

          <div class="followme">
  <span>Welcome to my other publishing channels</span>

  <div class="social-list">

      <div class="social-item">
          <a target="_blank" class="social-link" href="https://github.com/fantasy-ke">
            <span class="icon">
              <i class="fab fa-github"></i>
            </span>

            <span class="label">GitHub</span>
          </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/ASP-NET-Core/" rel="tag"><i class="fa fa-tag"></i> ASP.NET Core</a>
              <a href="/tags/gRPC/" rel="tag"><i class="fa fa-tag"></i> gRPC</a>
          </div>

        
  <div class="social-like a2a_kit a2a_kit_size_32 a2a_default_style">
    <a class="a2a_dd" target="_blank" rel="noopener" href="https://www.addtoany.com/share"></a>
      <a class="a2a_button_facebook"></a>
      <a class="a2a_button_twitter"></a>
      <a class="a2a_button_telegram"></a>
      <a class="a2a_button_wechat"></a>
  </div>

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/posts/2248/" rel="prev" title="EntityFramework Core的并发处理">
                  <i class="fa fa-angle-left"></i> EntityFramework Core的并发处理
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/posts/48383/" rel="next" title="MediatR：轻松实现命令查询职责分离模式(CQRS)">
                  MediatR：轻松实现命令查询职责分离模式(CQRS) <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments gitalk-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2021 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-solid fa-t-rex"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Fantasy-ke</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>Word count total: </span>
    <span title="Word count total">72k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>Reading time total &asymp;</span>
    <span title="Reading time total">4:21</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="Total Visitors">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="Total Views">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div> 
<script src="https://cdn.jsdelivr.net/npm/moment@2.22.2/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment-precise-range-plugin@1.3.0/moment-precise-range.min.js"></script>
<script>
  var now = new Date();
  function timer() {
    var grt= new Date("03/12/2022 13:14:21");//此处修改你的建站时间或者网站上线时间
    now.setTime(now.getTime()+250);
    days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
    hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
    if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
    seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
    var ages = `${dnum}天${hnum}小时${mnum}分${snum}秒`;
    div.innerHTML = `本站已安全运行 ${ages} 🐶`;
  }
  var div = document.createElement("div");
  //插入到copyright之后
  var copyright = document.querySelector(".busuanzi-count");
  document.querySelector(".footer-inner").insertBefore(div, copyright.nextSibling);
  timer();
  setInterval("timer()",1000)
</script>


<div class="footer-menu">
    <a style="color: chocolate;" href="/tags/">文章标签</a> · <a style="color: chocolate;"  href="/policy/">网站政策</a> · <a style="color: chocolate;"  href="/photos/">文章相册</a>
</div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL2ZhbnRhc3kta2U=" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.31/fancybox/fancybox.umd.js" integrity="sha256-a+H7FYzJv6oU2hfsfDGM2Ohw/cR9v+hPfxHCLdmCrE8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>


  <script src="/js/third-party/addtoany.js"></script>

  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script>

<script>
var options = {
  bottom: '64px',
  right: 'unset',
  left: '32px',
  time: '0.5s',
  mixColor: 'transparent',
  backgroundColor: 'transparent',
  buttonColorDark: '#100f2c',
  buttonColorLight: '#fff',
  saveInCookies: true,
  label: '🌓',
  autoMatchOsTheme: true
}
const darkmode = new Darkmode(options);
window.darkmode = darkmode;
darkmode.showWidget();
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.8.0/gitalk.css" integrity="sha256-AJnUHL7dBv6PGaeyPQJcgQPDjt/Hn/PvYZde1iqfp8U=" crossorigin="anonymous">

<script class="next-config" data-name="gitalk" type="application/json">{"enable":true,"github_id":"fantasy-ke","repo":"fantasy-ke.github.io","client_id":"Ov23li8eCFrhnzfiGx5T","client_secret":"ce23581c2059392ebd00afd08d5ba43f767fd1b1","admin_user":"fantasy-ke","distraction_free_mode":true,"proxy":"https://cors-anywhere.azm.workers.dev/https://github.com/login/oauth/access_token","language":"zh-CN","labels":"gitalk","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.8.0/gitalk.min.js","integrity":"sha256-MVK9MGD/XJaGyIghSVrONSnoXoGh3IFxLw0zfvzpxR4="},"path_md5":"8e2e60430fcbfcc7043eb2320c62b51d"}</script>
<script src="/js/third-party/comments/gitalk.js"></script>


<script src="/js/minigrid.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script data-pjax type="text/javascript">
var album = document.querySelector(".album");
if (album) {
  // 相册列表 JSON 数据
  var imgDataPath = album.getAttribute('json-src');
  // 照片存储路径
  var imgPath = album.getAttribute('photo-src');
  // 最多显示数量
  var imgMaxNum = 50;
  // 获取窗口大小以决定图片宽度
  var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  var imageWidth;

  if (windowWidth < 768) {
    imageWidth = 145; // 移动端图片宽度
  } else {
    imageWidth = 235;
  }

  // 生成相册
  var linkDataPath = imgDataPath;
  var photo = {
    page: 1,
    offset: imgMaxNum,
    init: function () {
      var that = this;
      $.getJSON(linkDataPath, function (data) {
          that.render(that.page, data);
      });
    },
    render: function (page, data) {
      var begin = (page - 1) * this.offset;
      var end = page * this.offset;
      if (begin >= data.length) return;
      var imgNameWithPattern, imgName, imageSize, imageX, imageY, li = "";
      for (var i = begin; i < end && i < data.length; i++) {
        imgNameWithPattern = data[i].path;
        imgName = data[i].name;
        imageSize = data[i].size;
        li += '<div class="card" style="width:' + imageWidth + 'px" >';
        li += '<div class="album-photo" style="height:' + imageWidth + 'px" >';
        li += '<a class="fancybox fancybox.image" href="' + imgPath + imgNameWithPattern + '" itemscope="" itemtype="http://schema.org/ImageObject" itemprop="url" data-fancybox="group" rel="group" data-caption="' + imgName + '" title="' +  imgName + '">';
        li += '<img data-src="' + imgPath + imgNameWithPattern + '" src="' + imgPath + imgNameWithPattern + '" alt="' +  imgName + '" data-loaded="true">';
        li += '</a>';
        li += '</div>';
        li += '</div>';
      }
      album.insertAdjacentHTML('beforeend', li);
      this.minigrid();
    },
    minigrid: function () {
      var grid = new Minigrid({
        container: '.album',
        item: '.card',
        gutter: 12
      });
      grid.mount();
      window.addEventListener('resize', function () {
        grid.mount();
      });
    }
  };
  photo.init();
}
</script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":170,"height":330},"mobile":{"show":true},"react":{"opacity":0.7},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
